package com.studentmanagement.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.studentmanagement.model.PageBean;
import com.studentmanagement.model.Student;
import com.studentmanagement.service.StudentService;

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 显示学生列表
     */
    @GetMapping("")
    public String list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                       @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                       @RequestParam(value = "sortField", defaultValue = "studentId") String sortField,
                       @RequestParam(value = "sortOrder", defaultValue = "ASC") String sortOrder,
                       Model model) {
        // 获取分页数据
        PageBean<Student> pageBean = studentService.getStudentsByPage(pageNum, pageSize, sortField, sortOrder);

        // 将数据存入模型
        model.addAttribute("pageBean", pageBean);

        return "student/list";
    }

    /**
     * 显示添加学生表单
     */
    @GetMapping("/add")
    public String showAddForm() {
        return "student/add";
    }

    /**
     * 处理添加学生请求
     */
    @PostMapping("/add")
    public String add(@RequestParam("name") String name,
                      @RequestParam("gender") String gender,
                      @RequestParam("birthDate") String birthDateStr,
                      @RequestParam("address") String address,
                      @RequestParam("phone") String phone,
                      @RequestParam("email") String email,
                      @RequestParam("enrollmentDate") String enrollmentDateStr,
                      @RequestParam("major") String major,
                      @RequestParam("status") String status,
                      Model model) {
        try {
            // 解析日期
            Date birthDate = dateFormat.parse(birthDateStr);
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);

            // 创建学生对象
            Student student = new Student();
            student.setName(name);
            student.setGender(gender);
            student.setBirthDate(birthDate);
            student.setAddress(address);
            student.setPhone(phone);
            student.setEmail(email);
            student.setEnrollmentDate(enrollmentDate);
            student.setMajor(major);
            student.setStatus(status);

            // 添加学生
            boolean success = studentService.addStudent(student);

            if (success) {
                // 添加成功，重定向到列表页面
                return "redirect:/student";
            } else {
                // 添加失败，设置错误消息
                model.addAttribute("error", "添加学生失败");
                return "student/add";
            }
        } catch (ParseException e) {
            e.printStackTrace();
            model.addAttribute("error", "日期格式错误");
            return "student/add";
        }
    }

    /**
     * 显示编辑学生表单
     */
    @GetMapping("/edit")
    public String showEditForm(@RequestParam("id") Integer studentId, Model model) {
        // 获取学生信息
        Student student = studentService.getStudentById(studentId);

        if (student != null) {
            // 将学生信息存入模型
            model.addAttribute("student", student);

            return "student/edit";
        } else {
            // 学生不存在，重定向到列表页面
            return "redirect:/student";
        }
    }

    /**
     * 处理编辑学生请求
     */
    @PostMapping("/edit")
    public String edit(@RequestParam("studentId") Integer studentId,
                       @RequestParam("name") String name,
                       @RequestParam("gender") String gender,
                       @RequestParam("birthDate") String birthDateStr,
                       @RequestParam("address") String address,
                       @RequestParam("phone") String phone,
                       @RequestParam("email") String email,
                       @RequestParam("enrollmentDate") String enrollmentDateStr,
                       @RequestParam("major") String major,
                       @RequestParam("status") String status,
                       Model model) {
        try {
            // 解析日期
            Date birthDate = dateFormat.parse(birthDateStr);
            Date enrollmentDate = dateFormat.parse(enrollmentDateStr);

            // 创建学生对象
            Student student = new Student();
            student.setStudentId(studentId);
            student.setName(name);
            student.setGender(gender);
            student.setBirthDate(birthDate);
            student.setAddress(address);
            student.setPhone(phone);
            student.setEmail(email);
            student.setEnrollmentDate(enrollmentDate);
            student.setMajor(major);
            student.setStatus(status);

            // 更新学生
            boolean success = studentService.updateStudent(student);

            if (success) {
                // 更新成功，重定向到列表页面
                return "redirect:/student";
            } else {
                // 更新失败，设置错误消息
                model.addAttribute("error", "更新学生失败");
                model.addAttribute("student", student);
                return "student/edit";
            }
        } catch (ParseException e) {
            e.printStackTrace();
            model.addAttribute("error", "日期格式错误");

            // 获取原学生信息
            Student student = studentService.getStudentById(studentId);
            model.addAttribute("student", student);

            return "student/edit";
        }
    }

    /**
     * 处理删除学生请求
     */
    @GetMapping("/delete")
    public String delete(@RequestParam("id") Integer studentId) {
        // 删除学生
        studentService.deleteStudent(studentId);

        // 重定向到列表页面
        return "redirect:/student";
    }
}